package cn.craftyun.yunexam.controller;

import cn.craftyun.yunexam.entity.AdminUser;
import cn.craftyun.yunexam.request.AdminUserLoginRequest;
import cn.craftyun.yunexam.service.AdminUserService;
import cn.craftyun.yunexam.vo.ResultEntity;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@Log4j2
@RestController
@RequestMapping("/adminUser")
public class AdminUserController {
    @Resource
    private AdminUserService adminUserService;

    @PostMapping("/login")
    public ResultEntity login(@RequestBody @Valid AdminUserLoginRequest adminUserLoginRequest, HttpServletRequest request) {
        AdminUser user = adminUserService.findByUsername(adminUserLoginRequest.getUsername());
        if (user == null) {
            return ResultEntity.error("用户不存在", null);
        }
        if (!adminUserLoginRequest.getPassword().equals(user.getPassword())) {
            return ResultEntity.error("用户密码错误", null);
        }
        // 抹去用户的密码
        user.setPassword(null);
        // 设置session
        request.getSession().setAttribute("adminUser", user);
        // 返回登录成功的结果
        return ResultEntity.success("登录成功", user);
    }

    @PostMapping("/logout")
    public ResultEntity logout(HttpServletRequest request) {
        request.getSession().removeAttribute("adminUser");
        return ResultEntity.success("退出成功", null);
    }
}
